package com.zx.zxpicture.application.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zx.zxpicture.domain.space.service.SpaceDomainService;
import com.zx.zxpicture.infrstructure.common.BaseResponse;
import com.zx.zxpicture.infrstructure.common.ErrorCode;
import com.zx.zxpicture.infrstructure.common.ResultUtils;
import com.zx.zxpicture.infrstructure.exception.BusinessException;
import com.zx.zxpicture.infrstructure.exception.ThrowUtils;
import com.zx.zxpicture.interfaces.dto.space.SpaceAddRequest;
import com.zx.zxpicture.interfaces.dto.space.SpaceLevel;
import com.zx.zxpicture.interfaces.dto.space.SpaceQueryRequest;
import com.zx.zxpicture.domain.space.entity.Space;
import com.zx.zxpicture.domain.space.entity.SpaceUser;
import com.zx.zxpicture.domain.user.entity.User;
import com.zx.zxpicture.domain.space.valueObject.SpaceLevelEnum;
import com.zx.zxpicture.domain.space.valueObject.SpaceRoleEnum;
import com.zx.zxpicture.domain.space.valueObject.SpaceTypeEnum;
import com.zx.zxpicture.interfaces.vo.SpaceVO;
import com.zx.zxpicture.interfaces.vo.UserVO;
import com.zx.zxpicture.application.service.SpaceApplicationService;
import com.zx.zxpicture.infrstructure.mapper.SpaceMapper;
import com.zx.zxpicture.application.service.SpaceUserApplicationService;
import com.zx.zxpicture.application.service.UserApplicationService;
import com.zx.zxpicture.infrstructure.utils.LockUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
* @author ZX
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-02-27 15:31:03
*/
@Service
@Slf4j
public class SpaceApplicationServiceImpl extends ServiceImpl<SpaceMapper,Space> implements SpaceApplicationService {
    @Resource
    private SpaceDomainService spaceDomainService;
    @Resource
    private TransactionTemplate transactionTemplate; //方法事务
    @Resource
    private UserApplicationService userApplicationService;
    @Resource
    @Lazy
    private SpaceUserApplicationService spaceUserApplicationService;
//    @Resource
//    @Lazy
//    private DynamicShardingManager dynamicShardingManager;

    /**
     * 校验空间参数
     * @param space
     * @add 用来标识是添加空间还是修改空间
     */
    @Override
    public void validSpace(Space space,Boolean add) {
        spaceDomainService.validSpace(space,add);
    }

        /**
         * 创建空间
         * @param spaceAddRequest
         * @param loginUser
         * @return 空间id
         */
        @Override
        public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
            //将请求类转换为实体类
            Space space = new Space();
            BeanUtil.copyProperties(spaceAddRequest, space);
            //判断是否有值，没有值给默认值
            if(StrUtil.isBlank(space.getSpaceName())){
                space.setSpaceName("默认空间");
            }
            if(space.getSpaceLevel() == null){
                space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
            }
            if(space.getSpaceType() == null){
                //默认为私有空间
                space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
            }
            //填充数据
            fillSpaceBySpaceLevel(space);
            //校验
            validSpace(space,true);
            Long userId = loginUser.getId();
            space.setUserId(loginUser.getId());
            //创建空间
            ConcurrentHashMap<Long, Object> concurrentHashMap = new ConcurrentHashMap<>();
            //获取锁(用户级别的锁)
            if(!LockUtils.tryLock("spaceAdd" + userId)){
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"请勿重新创建个人空间");
            }
            try {
                //开启事务
                //在回调函数执行完后提交事务
                Long newSpaceId = transactionTemplate.execute(status -> {
                    //先查看空间是否存在
                    boolean exists = spaceDomainService.lambdaQuery()
                            .eq(Space::getUserId, userId)
                            //每个用户只能创建一个私人或团队空间
                            .eq(Space::getSpaceType, space.getSpaceType())
                            .exists();
                    if(exists){
                        throw new BusinessException(ErrorCode.OPERATION_ERROR,"请勿重新创建个人或团队空间");
                    }
                    //创建空间
                    boolean save = spaceDomainService.save(space);
                    if(!save) {
                        throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建个人或团队失败");
                    }
                    //如果是团队空间，关联新增团队成员记录（团队空间管理员）
                    if(space.getSpaceType() == SpaceTypeEnum.TEAM.getValue()){
                        SpaceUser spaceUser = new SpaceUser();
                        spaceUser.setSpaceId(space.getId());
                        spaceUser.setUserId(userId);
                        spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                        boolean save1 = spaceUserApplicationService.save(spaceUser);
                        ThrowUtils.throwIf(!save1, ErrorCode.OPERATION_ERROR,"创建团队成员记录失败");
                    }
//                    //创建分表
//                    if(space.getSpaceType() == SpaceTypeEnum.TEAM.getValue() && space.getSpaceLevel() == SpaceLevelEnum.FLAGSHIP.getValue()){
//                        //如果为旗舰版团队空间，创建分表
//                        dynamicShardingManager.createSpacePictureTable(space);
//                    }
                    return space.getId();
                });
                log.info("事务提交成功");
                return newSpaceId;
            }finally {
                //防止内存泄漏
                LockUtils.unlock("spaceAdd" + userId);
                log.info("开始释放锁");
            }
        }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        return spaceDomainService.getQueryWrapper(spaceQueryRequest);
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        // 对象转封装类
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        // 关联查询用户信息
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userApplicationService.getById(userId);
            UserVO userVO = userApplicationService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    /**
     * 获取空间封装列表
     * @param spacePage
     * @param request
     * @return
     */
    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        //创建新的分页对象
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if(spaceList.isEmpty()){
            spaceVOPage.setRecords(List.of());
            return spaceVOPage;
        }

        // 对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVo).collect(Collectors.toList());
        //遍历图片集合，整合用户id
        Set<Long> userIds = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        //查询所有用户数据
        Map<Long, List<User>> usersMap = userApplicationService.listByIds(userIds).stream().collect(Collectors.groupingBy(User::getId));
        //填充用户信息
        spaceVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (usersMap.containsKey(userId)) {
                user = usersMap.get(userId).get(0);
            }
            pictureVO.setUser(userApplicationService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    /**
     * 根据空间级别，自动填充限额
     * 如果管理员上传了限额，则不进行自动填充
     * @param space
     */
    @Override
    public void fillSpaceBySpaceLevel(Space space) {
      spaceDomainService.fillSpaceBySpaceLevel(space);
    }

    /**
     * 校验空间权限
     * @param loginUser
     * @param space
     */
    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        Long spaceUserId = space.getUserId();
        //你不是空间管理员，又不是管理员，报错
        if(!spaceUserId.equals(loginUser.getId()) && !userApplicationService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有权限操作该空间");
        }
    }

    @Override
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

    @Override
    public Space getById(Long spaceId) {
        return spaceDomainService.getById(spaceId);
    }

    @Override
    public Collection<Space> listByIds(Set<Long> spaceIdSet) {
        return spaceDomainService.listByIds(spaceIdSet);
    }
}




